import datetime

import requests, json


def get_weather_by_city(city = "北京", response_way = "default"):
    """
    获取天气的方法
    :param city:
    :param response_way: [default]/[useInput]/[onlyPrint]
    :return:
    """

    # 先对传入城市做字符串处理,去除所有市和县
    city = city.replace("县", "").replace("市", "")

    #api地址
    url = 'http://t.weather.sojson.com/api/weather/city/'
    # 读取json文件
    f = open('../weather/city.json', 'rb')
    # 使用json模块的load方法加载json数据，返回一个字典
    cities = json.load(f)
    # 通过城市的中文获取城市代码
    city = cities.get(city)
    if city == None:
        print("未找到当前城市，查询失败")
        city = cities.get("北京")
    # 网络请求，传入请求api+城市代码
    response = requests.get(url + city)
    # 将数据以json形式返回，这个d就是返回的json数据
    result = response.json()
    if (result['status'] != 200):
        data = "请求状态异常,请联系程序人员"
        return data

    if response_way == "default":
        data = "城市:{} {} \n查询时间:{} \n报告时间:{} \n温度:{} \n天气:{}"\
            .format(result["cityInfo"]["parent"], result["cityInfo"]["city"],
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), result["time"],
                    result["data"]["forecast"][0]["week"], result["data"]["forecast"][0]["high"],
                    result["data"]["forecast"][0]["low"], result["data"]["forecast"][0]["type"])
    elif response_way == "useInput":
        data = "城市:{} {} [Enter]查询时间:{} [Enter]报告时间:{} [Enter]温度:{} [Enter]天气:{}" \
            .format(result["cityInfo"]["parent"], result["cityInfo"]["city"],
                    datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), result["time"],
                    result["data"]["forecast"][0]["week"], result["data"]["forecast"][0]["high"],
                    result["data"]["forecast"][0]["low"], result["data"]["forecast"][0]["type"])
        data = data.replace("[Enter]", "{Enter}")
    elif response_way == "onlyPrint":
        data = 0
        print("城市：", result["cityInfo"]["parent"], result["cityInfo"]["city"])
        print("查询时间：{}".format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
        print("报告时间：", result["time"], result["data"]["forecast"][0]["week"])
        print("温度：", result["data"]["forecast"][0]["high"], result["data"]["forecast"][0]["low"])
        print("天气：", result["data"]["forecast"][0]["type"])

    return data

#当返回状态码为200，输出天气状况
if __name__ == "__main__":
    get_weather_by_city("银川", response_way= "onlyPrint")